<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span style="line-height: 36px;">报销单申请</span>
      </div>
      <div>
        <s-card :card="card" @cardClick="dialogOpen" :key="card.title" v-for="card in cards"></s-card>
      </div>
    </el-card>
    <s-dialog :dialog="dialog"  :closeTip="false" :close="dialogInit">
      <div>
        <s-form :form="formDialog" ref="formDialog">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span style="line-height: 36px; font-size: 20px">{{dialog.card.title}}</span>
              <span class="process">报销编号：{{formDialog.reimbursementCode}}</span>
              <span class="process">当前流程： </span>
              <el-select v-model="formDialog.workflowconfigId"
                         class="process_select"
                         placeholder="请选择">
                <el-option
                  v-for="item in dialog.process.data"
                  :key="item.value"
                  :label="item.processName + '   ' +  item.departmentName"
                  :value="item.id">
                </el-option>
              </el-select>
              <el-checkbox
                class="process"
                v-model="dialog.process.option.default">默认流程</el-checkbox>
              <el-button class="process process_download" size="mini" type="info" v-if="dialog.card.title === '成本费用报销单' || dialog.card.title === '奖励扣款报销单'" @click="download">模板下载</el-button>
              <el-button class="process process_download" size="mini" type="primary" v-if="dialog.card.title === '成本费用报销单' || dialog.card.title === '奖励扣款报销单'" @click="dialogDownloadOpen">导入</el-button>
            </div>
            <el-row>
              <el-col :xs="24" :lg="{span: 11, offset: 0}">
                <el-form-item prop="reimbursementDate" :label="dialog.card.title !== '结算单' ? '报销日期' : '结算日期'">
                  <el-date-picker
                    v-model="formDialog.reimbursementDate"
                    disabled
                    format="yyyy年 MM月 dd日"
                    type="date"
                    placeholder="选择日期">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :lg="{span: 11, offset: 1}" v-if="dialog.card.title !== '暂借款借支单'">
                <el-form-item label="报销部门">
                  <div class="s-content">
                    <!--<el-tag type="success">{{USER.user.orgName}}</el-tag>-->
                    <el-select v-model="formDialog.departmentId" style="width: 10rem;" placeholder="请选择">
                      <el-option
                        v-for="item in this.useroptions.options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                      </el-option>
                    </el-select>
                    <el-button type="primary" style="float: right" v-if="dialog.card.title === '差旅费用报销单'" @click.prevent="addTravelUser">添加出差人员</el-button>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
            <div v-if="dialog.card.title === '差旅费用报销单'">
              <el-row
                :key="index"
                v-for="(item, index) in formDialog.travel">
                <el-col :xs="24" :lg="{span: 9, offset: 0}">
                  <el-form-item
                    :prop="'travel.' + index + '.user'"
                    :label="'出差人员 ' + (index + 1)"
                    :rules="{required: true, message: '出差人员不能为空', trigger: 'blur'}">
                    <el-input
                      type="text"
                      v-model="item.user"
                      placeholder="出差人员"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :lg="{span: 9, offset: 1}">
                  <el-form-item :prop="'travel.' + index + '.level'"
                                :label="'职位等级 ' + (index + 1)"
                                :rules="{required: true, message: '职位等级不能为空', trigger: 'blur'}">
                    <el-input
                      type="text"
                      v-model="item.level"
                      :placeholder="`出差人员 ${(index + 1)} 的职位等级`"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :lg="{span: 3, offset: 1}">
                  <el-form-item label="可用操作">
                    <div class="s-content">
                      <el-button
                        size="mini"
                        icon="el-icon-delete"
                        round
                        type="danger"
                        @click.prevent="removeTravelUser(item)">删除</el-button>
                    </div>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :xs="24" :lg="{span: 11, offset: 0}">
                  <el-form-item prop="attributionDate" label="归属期间">
                    <el-date-picker
                      :clearable="false"
                      v-model="formDialog.attributionDate"
                      type="month"
                      placeholder="归属周期">
                    </el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :lg="{span: 11, offset: 1}">
                  <el-form-item prop="travelReason" label="出差事由">
                    <el-input
                      type="text"
                      v-model="formDialog.travelReason"
                      placeholder="出差事由"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
            <div v-if="dialog.card.title === '暂借款借支单'">
              <el-row>
                <el-col :xs="24" :lg="{span: 11, offset: 0}">
                  <el-form-item prop="borrower" label="借款人 ">
                    <div class="s-content">
                      {{USER.user.name}}
                    </div>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :lg="{span: 11, offset: 1}">
                  <el-form-item label="所属部门">
                    <div class="s-content">{{USER.user.orgName}}</div>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :xs="24" :lg="{span: 11, offset: 0}">
                  <el-form-item prop="loanProject" label="借款项目  ">
                    <el-input
                      type="text"
                      v-model="formDialog.loanProject"
                      placeholder="借款项目"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :lg="{span: 11, offset: 1}">
                  <el-form-item prop="loanMoney" label="借款金额 ">
                    <el-input
                      type="text"
                      v-model="formDialog.loanMoney"
                      placeholder="借款金额"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :xs="24" :lg="{span: 11, offset: 0}">
                  <el-form-item prop="repaymentDate" label="还款时间  ">
                    <el-date-picker
                      v-model="formDialog.repaymentDate"
                      type="date"
                      :editable="false"
                      placeholder="还款时间"
                      :picker-options="pickerOptions">
                    </el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :lg="{span: 11, offset: 1}">
                  <el-form-item prop="loanMoneyCap" label="借款金额(大写) ">
                    <div class="s-content">
                      {{formDialog.loanMoneyCap}}
                    </div>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
            <el-collapse :value="['1', '2', '3', '4']" class="__rbApply">
              <el-collapse-item :title="dialog.card.title === '结算单' ? '结算明细 (提示： 按住 shift  使用 鼠标滑轮 控制横向滚动页面)' : '报销明细'" name="1" v-if="dialog.card.title !== '暂借款借支单'">
                <expense v-if="dialog.card.title === '成本费用报销单'" ref="details" @change="handleDetailsChange"></expense>
                <travel v-if="dialog.card.title === '差旅费用报销单'" ref="details" @change="handleDetailsChange2"></travel>
                <rewardDeduction v-if="dialog.card.title === '奖励扣款报销单'" ref="details" @change="handleDetailsChange3"></rewardDeduction>
                <adviceSettlement v-if="dialog.card.title === '结算单'" ref="details" @change="handleDetailsChange4"></adviceSettlement>
              </el-collapse-item>
              <el-row class="other" v-if="dialog.card.title !== '暂借款借支单' && dialog.card.title !== '结算单'">
                <el-col :xs="24" :lg="{span: 4, offset: 0}" v-if="dialog.card.title === '成本费用报销单'">
                  <el-form-item prop="isWithholding" label="是否预提">
                    <el-switch
                      v-model="formDialog.isWithholding"
                      active-text="是"
                      :active-value="2"
                      :inactive-value="1"
                      inactive-text="否"
                      active-color="#13ce66"
                      inactive-color="#ff4949">
                    </el-switch>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :lg="{span: 4, offset: dialog.card.title === '成本费用报销单' ? 1 : 0}">
                  <el-form-item label="报销金额合计">
                    {{SplitK(formDialog.money)}}
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :lg="{span: 8, offset: 1}">
                  <el-form-item pr label="核实金额（大写）">
                    {{formDialog.moneyCap}}
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :lg="{span: 4, offset: 1}" v-if="formDialog.borrowingMoney !== -1">
                  <el-form-item label="借款金额合计">
                    {{SplitK(formDialog.borrowingMoney)}}
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row class="other" v-if="dialog.card.title === '结算单'">
                <el-col :xs="24" :lg="{span: 4, offset: 0}">
                  <el-form-item label="报销金额合计">
                    {{SplitK(formDialog.money)}}
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :lg="{span: 8, offset: 1}">
                  <el-form-item label="核实金额（大写）">
                    {{formDialog.moneyCap}}
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :lg="{span: 4, offset: 1}">
                  <el-form-item label="油卡金额">
                    {{SplitK(formDialog.moneyYouKa)}}
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :lg="{span: 4, offset: 1}">
                  <el-form-item label="现金金额">
                    {{SplitK(formDialog.moneyXianJin)}}
                  </el-form-item>
                </el-col>
              </el-row>
              <el-collapse-item title="收款方" name="4" v-if="dialog.card.title === '差旅费用报销单' || dialog.card.title === '暂借款借支单'">
                <payee ref="payee" :card="dialog.card" :travel="dialog.card.title === '差旅费用报销单'"></payee>
              </el-collapse-item>
              <el-collapse-item title="附件列表" name="2">
                <el-upload
                  :action="action"
                  :multiple="true"
                  name="reimbursement_image"
                  list-type="picture-card"
                  ref="upload"
                  :before-upload="dialogUploadBefore"
                  :before-remove="handleBeforeRemove"
                  :on-preview="handlePictureCardPreview"
                  :on-remove="handleRemove">
                  <i class="el-icon-plus"></i>
                </el-upload>
                <p>附件数量：  {{$refs.upload ? $refs.upload.uploadFiles.length : 0}}</p>
              </el-collapse-item>
            </el-collapse>
          </el-card>
        </s-form>
      </div>
      <el-button slot="footer" @click="dialogSave">保存草稿</el-button>
      <el-button slot="footer" type="primary" @click="dialogSave(1)">直接提交</el-button>
    </s-dialog>
    <v-viewer :options="viewer.option" :images="viewer.images"
              @inited="viewerInit" ref="viewer">
      <template scope="scope">
        <ul id="viewer">
          <li v-for="image in scope.images" :key="image">
            <img :src="image"/>
          </li>
        </ul>
      </template>
    </v-viewer>
    <s-dialog :dialog="dialogUpload">
      <p slot="title">申请审核报销单</p>
      <s-form :form="formDialogUpload" ref="formDialogUpload">
        <el-row>
          <el-col :xs="24" :lg="{span: 23, offset: 0}" class="">
            <el-form-item prop="nextAuditorId" label="审核人">
              <el-select v-model="formDialogUpload.nextAuditorId"
                         filterable
                         placeholder="请选择">
                <el-option
                  v-for="item in dialogUpload.userId"
                  :key="item.id"
                  :label="item.name + '   ' + item.orgName"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </s-form>
      <el-button slot="footer" @click="dialogUploadSave">保存</el-button>
    </s-dialog>
    <s-dialog :dialog="dialogDownload">
      <p slot="title">上传EXCEL文件</p>
      <div style="margin: 0 20px">
        <el-upload
          :action="action"
          :multiple="true"
          drag
          name="reimbursement_image"
          ref="uploadExcel"
          :on-success="handleSuccessExcel"
          :on-remove="handleRemoveExcel">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">只能上传指定的模板文件，且不超过500MB</div>
        </el-upload>
      </div>
      <el-button slot="footer" @click="dialogDownloadSave">完成</el-button>
    </s-dialog>
  </div>
</template>

<script>
  /* eslint-disable keyword-spacing,quotes */

  import {AutoVue, AutoPromise, DownFile, SplitK, IsImage} from '~/plugins/Tools';
  import Config from '~/config';
  import sCard from '~/components/reimbursement/s-card.vue';
  import Expense from '~/components/reimbursement/expense.vue';
  import Travel from '~/components/reimbursement/travel.vue';
  import Payee from '~/components/reimbursement/payee.vue';
  import RewardDeduction from '~/components/reimbursement/rewardDeduction.vue';
  import AdviceSettlement from '~/components/reimbursement/adviceSettlement.vue';
  import Nzh from 'nzh';

  let {
    PublicImageServer,
  } = Config;
  function __cards () {
    return [
      {
        title: '成本费用报销单',
        code: 'expenseCost',
        body: 'test',
        img: 'apple',
      },
      {
        title: '差旅费用报销单',
        code: 'travelExpense',
        body: 'test',
        img: 'apple',
      },
      {
        title: '暂借款借支单',
        code: 'borrowing',
        body: 'test',
        img: 'apple',
      },
      {
        title: '结算单',
        code: 'adviceSettlement',
        body: 'test',
        img: 'apple',
      },
      {
        title: '奖励扣款报销单',
        code: 'rewardDeduction',
        body: 'test',
        img: 'apple',
      },
    ];
  }
  function __formDialog () {
    return {
      reimbursementDate: { value: new Date(), rule: [ 'vNull' ], type: 'Date' },
      departmentId: { value: '', rule: [ 'vNull' ] },
      reimbursementCode: { value: '', rule: [ 'vNull' ] },
      money: { value: 0, rule: [ 'vNull' ] },
      moneyYouKa: { value: '', rule: [] },
      moneyXianJin: { value: '', rule: [] },
      moneyCap: { value: Nzh.cn.toMoney(0), rule: [ 'vNull' ] },
      borrowingMoney: { value: 0, rule: [ 'vNull', 'vNumber' ] },
      enclosureNum: { value: 0, rule: [ 'vNumber' ] },
      workflowconfigId: { value: '', rule: [ 'vNull' ] },
      isWithholding: { value: 1, rule: [ 'vNull' ] },
      fileVoList: { value: '', rule: [] },
      orgName: { value: '', rule: [] },
      travel: {
        value: [
          {
            user: '',
            level: '',
          },
        ],
        rule: [] },
      travelUsers: { value: '', rule: ['vNull'] },
      positionLeave: { value: '', rule: ['vNull'] },
      attributionDate: { value: '', rule: ['vNull__change'], type: 'Date' },
      travelReason: { value: '', rule: ['vNull'] },
      ...__formDialog_borrowing(),
    };
  }
  function __formDialog_borrowing () {
    return {
      loanMoney: { value: '', rule: ['vNull'] },
      loanProject: { value: '', rule: ['vNull'] },
      loanMoneyCap: { value: '', rule: [] },
      repaymentDate: { value: '', rule: [], type: 'Date' },
    };
  }
  function __formDialogUpload () {
    return {
      nextAuditorId: { value: '', rule: ['vNull'], cRemarks: '' },
      id: { value: '', rule: [], cRemarks: '' },
    };
  }

  function tofixed (dt) {
    dt += '';
    let result;
    if (dt.indexOf('.') !== -1) {
      result = dt.substr(0, dt.indexOf('.') + 3);
    } else {
      result = dt;
    }
    return parseFloat(result);
  }

  function summation (hei, data) {
    let result = hei * 100 + data * 100;
    return result / 100;
  }

  export default AutoVue({
    data: {
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() > Date.now() + 15 * 24 * 60 * 60 * 1000 || time.getTime() < Date.now();
        },
      },
      dialog: {
        title: '新增',
        fullscreen: true,
        width: '100%',
        card: {},
        reimbursementUser: [],
        borrower: [],
        process: {
          data: [],
          option: {
            active: '',
            default: true,
          },
        },
      },
      formDialog: __formDialog(),
      dialogUpload: {
        userId: [],
      },
      formDialogUpload: __formDialogUpload(),
      cards: __cards(),
      dialogImage: {
        url: false,
        fullscreen: true,
        formRef: false,
        width: '100%',
      },
      viewer: {
        option: {
          zIndex: 100000,
        },
        el: {},
        images: [],
      },
      dialogDownload: {
        formRef: false,
        dialogCallBack: function () {
          this.$refs.uploadExcel.uploadFiles.forEach(item => {
            this.handleRemoveExcel(item);
          });
          this.$refs.uploadExcel.uploadFiles = [];
        },
      },
      useroptions: {
        options: '',
      },
      fileSize: 0,
      summation: 0,
    },
    computed: {
      action: function () {
        return PublicImageServer.src + '/file/upload/image/reimbursement';
      },
      server: function () {
        return PublicImageServer.src + '/image/reimbursement/';
      },
    },
    transition: 'slide-fade-bottom',
    head: {
      'title': '报销单申请',
      'meta': [
        { 'hid': 'description', 'name': 'description', 'content': '乐速科技平台 报销单管理 报销单申请' },
      ],
    },
    store: ['USER', 'TRAVEL_moneyUse', 'TRAVEL_moneySum'],
    components: {
      's-card': sCard,
      'expense': Expense,
      'travel': Travel,
      'payee': Payee,
      'rewardDeduction': RewardDeduction,
      'adviceSettlement': AdviceSettlement,
    },
    beforeRouteLeave (to, from, next) {
      this.$destroy();
      next();
    },
    methods: {
      SplitK,
      viewerInit (viewer) {
        this.viewer.el = viewer;
      },
      viewerShow () {
        this.$viewer.show();
      },
      dialogDownloadOpen () {
        this.dialogDownload.visible = true;
      },
      async handleSuccessExcel (response, file, fileList) {
        let expense = this.dialog.card.title === '成本费用报销单';
        let url = expense ? '/expense/importData' : '/rewardDeduction/import';
        let {data} = await this.post(url, {filename: this.server + response.filename});
        let details = this.$refs.details;
        let step = data;
        if (expense) {
          step = [];
          data.forEach(item => {
            item.isLoan = 1;
            item.loanState = 1;
            step.push(item);
          });
        }
        details.$set(details.table, 'data', [
          ...details.table.data,
          ...step,
        ]);
        details.$emit('change', details.table.data);
      },
      async handleRemoveExcel (file) {
        try {
          await this.p(this.action + '/' + file.response.filename, {
            method: 'delete',
            headers: {
              sLoading: true,
            },
          });
        } catch (err) {
          console.error(err);
        }
      },
      download () {
        let url = '';
        switch (this.dialog.card.title) {
        case '成本费用报销单': url = '成本费用.xlsx'; break;
        case '奖励扣款报销单': url = '奖励扣款.xlsx'; break;
        }
        DownFile(this.server + url, url);
      },
      dialogDownloadSave () {
        this.dialogDownload.dialogInit.call(this);
      },

      handleDetailsChange (data) {
        let money = 0;
        let borrowingMoney = 0;
        data.forEach(item => {
          money += item.money || 0;
          borrowingMoney += item.loanNum || 0;
        });
        this.formDialog.money = money;
        this.formDialog.moneyCap = Nzh.cn.toMoney(money);
        this.formDialog.borrowingMoney = borrowingMoney;
        return this.formDialog.money;
      },
      handleDetailsChange2 (data, type) {
        let money = 0;
        data.forEach(item => {
          let sum = summation(summation(tofixed(item.trafficMoney), tofixed(item.travelMoney)), tofixed(item.otherMoney));
          money = summation(money, sum);
        });
        this.formDialog.money = money;
        this.SET('TRAVEL_moneySum', money);
        if (type) {
          this.SET('TRAVEL_moneyUse', money);
        }
        this.formDialog.moneyCap = Nzh.cn.toMoney(money);
        console.log("moneyCap", this.formDialog.moneyCap);
        this.formDialog.borrowingMoney = -1;
        return this.formDialog.money;
      },
      handleDetailsChange3 (data) {
        let money = 0;
        data.forEach(item => {
          money = summation(money, tofixed(item.money));
        });
        this.formDialog.money = money;
        this.SET('TRAVEL_moneySum', money);
        this.formDialog.moneyCap = Nzh.cn.toMoney(money);
        this.formDialog.borrowingMoney = -1;
        return this.formDialog.money;
      },
      handleDetailsChange4 (data) {
        let money = 0;
        let moneyYouKa = 0;
        let moneyXianJin = 0;
        data.forEach(item => {
          let sum = summation(tofixed(item.oilcardSettleAmout), tofixed(item.cashAmout));
          money = summation(money, sum);
          console.log('moneyYouKa', moneyYouKa);
          moneyYouKa = summation(moneyYouKa, tofixed(item.oilcardSettleAmout));
          moneyXianJin = summation(moneyXianJin, tofixed(item.cashAmout));
        });
        this.formDialog.money = money;
        this.formDialog.moneyYouKa = moneyYouKa;
        this.formDialog.moneyXianJin = moneyXianJin;
        this.SET('TRAVEL_moneySum', money);
        this.formDialog.moneyCap = Nzh.cn.toMoney(money);
        this.formDialog.borrowingMoney = -1;
        return this.formDialog.money;
      },
      async dialogBorrower (query) {
        let {contentList} = await this.post('/empolyee/searchByPage', {
          bxSupplierName: query,
          'pageNumber': 1,
          'pageSize': 20,
        });
        this.dialog.borrower = contentList;
      },
      dialogBorrowerChange (id) {
        this.dialog.borrower.forEach(item => {
          if (item.id === id) {
            this.formDialog.departmentId = item.bxSupplierDepartmentid;
            this.formDialog.departmentName = item.bxSupplierDepartmentname;
          }
        });
      },

      dialogInit (type) {
        switch (this.dialog.card.title) {
        case '成本费用报销单':
          this.$refs.details.tableClear('table');
          this.$refs.details.loanNum = {};
          break;
        case '差旅费用报销单':
          this.DEL('TRAVEL_money');
          this.$refs.details.sTable.data = [];
          this.$refs.payee.tableClear('table');
          break;
        case '暂借款借支单':
          this.DEL('TRAVEL_money');
          this.$refs.payee.tableClear('table');
          break;
        case '结算单':
          this.$refs.details.sTable.data = [];
          this.$refs.details.sTable.old = [];
          break;
        case '奖励扣款报销单':
          this.DEL('TRAVEL_money');
          this.$refs.details.tableClear('table');
          break;
        }
        if (!type) {
          this.$refs.upload.uploadFiles.forEach(item => {
            this.handleRemove(item);
          });
        }
        this.$refs.upload.uploadFiles = [];
        this.dialog.dialogInit.call(this);
      },
      async dialogOpen (card) {
        this.dialog.visible = true;
        let autoPromise = [
          async () => {
            let {contentList} = await this.post('/workflowConfig/selectWorkflow', {
              'processType': card.code,
            });
            this.dialog.process.data = contentList;
            this.formDialog.workflowconfigId = window.localStorage['workflowconfigId_' + card.code] || (contentList[0] ? contentList[0].id : '');
          },
          async () => {
            let {number} = await this.get('/reimbursement/createNumber/' + this.USER.user.orgId);
            this.formDialog.reimbursementCode = number;
          },
        ];
        this.formDialog.reimbursementUser = this.USER.user.id;
        switch (card.title) {
        case '差旅费用报销单':
          autoPromise.push(async () => {
            this.reimbursementUser(this.USER.user.name);
          });
          break;
        case '暂借款借支单':
          autoPromise.push(async () => {
            this.dialogBorrower();
          });
          break;
        case '结算单':
          break;
        case '奖励扣款报销单':
          break;
        }
        await AutoPromise(autoPromise);
        this.dialog.card = card;
      },
      async reimbursementUser (query = '') {
        let {contentList} = await this.post('/empolyee/searchByPage', {
          bxSetlecycleName: query,
          'pageNumber': 1,
          'pageSize': 20});
        this.dialog.reimbursementUser = contentList;
      },
      // 删除文件的钩子
      async handleRemove (file) {
        try {
          await this.p(this.action + '/' + file.response.filename, {
            method: 'delete',
            headers: {
              sLoading: true,
            },
          });
          let size = file.size;
          this.fileSize -= size;
        } catch (err) {
          console.error(err);
        }
      },
      handlePictureCardPreview (file) {
        if (IsImage(file.name)) {
          let images = [];
          let index = 0;
          let length = 0;
          this.$refs.upload.uploadFiles.forEach((item, i) => {
            if (IsImage(item.name)) {
              images.push(item.url);
              if (file.response.filename === item.response.filename) {
                index = length;
              }
              length++;
            }
          });
          this.viewer.images = images;
          setTimeout(() => {
            this.viewer.el.index = index;
            this.viewer.el.view(index);
            this.viewer.el.show();
          }, 250);
        } else {
          DownFile(this.server + file.response.filename, file.response.filename);
        }
      },
      dialogSave (flag) {
        async function OPTION (option) {
          if (option.borrowingMoney === -1) {
            delete option.borrowingMoney;
          }
          try {
            option.enclosureNum = this.$refs.upload.uploadFiles.length;
          } catch (err) {
            option.enclosureNum = 0;
          }
          if (this.dialog.process.option.default) {
            window.localStorage.setItem('workflowconfigId_' + this.dialog.card.code, this.formDialog.workflowconfigId);
          } else {
            window.localStorage.removeItem('workflowconfigId_' + this.dialog.card.code);
          }
          let fileVoList = [];
          try {
            this.$refs.upload.uploadFiles.forEach(item => {
              fileVoList.push({fileUrl: item.response.filename});
            });
          } catch (err) {
            console.error(err);
          }
          let json = {};
          switch (this.dialog.card.title) {
          case '成本费用报销单':
            json = await this.post('/reimbursement', {
              reimbursementType: 'expenseCost',
              ...option,
              expenseCostFormDetailVoList: this.$refs.details.table.data,
              fileVoList,
            });
            this.dialogInit(1);
            break;
          case '差旅费用报销单':
            option.travelUsers = '';
            option.positionLeave = '';
            option.travel.forEach(item => {
              option.travelUsers += item.user + ';';
              option.positionLeave += item.level + ';';
            });
            delete option.travel;
            json = await this.post('/reimbursement', {
              reimbursementType: 'travelExpense',
              ...option,
              travelExpensesFormDetailVoList: this.$refs.details.sTable.data,
              payeeList: this.$refs.payee.table.data,
              fileVoList,
            });
            this.dialogInit(1);
            break;
          case '暂借款借支单':
            json = await this.post('/reimbursement', {
              reimbursementType: 'borrowing',
              ...option,
              money: option.loanMoney,
              moneyCap: option.loanMoneyCap,
              borrowingVoList: this.ObjectClone(__formDialog_borrowing(), option),
              payeeList: this.$refs.payee.table.data,
              fileVoList,
            });
            this.dialogInit(1);
            break;
          case '奖励扣款报销单':
            json = await this.post('/reimbursement', {
              reimbursementType: 'rewardDeduction',
              ...option,
              rewardDeductionVoList: this.$refs.details.table.data,
              fileVoList,
              borrowingMoney: -1,
            });
            this.dialogInit(1);
            break;
          case '结算单':
            json = await this.post('/reimbursement', {
              reimbursementType: 'adviceSettlement',
              ...option,
              settlementInfoVoList: this.$refs.details.sTable.old,
              fileVoList,
            });
            this.dialogInit(1);
            break;
          }
          if (flag === 1) {
            this.formDialogUpload.id = json.data;
            this.dialogUploadOpen();
          }
        }
        if (flag === 1) {
          if (this.dialog.card.title !== '结算单' ? (typeof this.$refs.upload !== 'undefined' && this.$refs.upload.uploadFiles.length > 0) : true) {
            if (this.formDialog.money || this.dialog.card.title === '暂借款借支单') {
              this.VALIDATE('formDialog', option => {
                switch (this.dialog.card.title) {
                case '成本费用报销单':
                  break;
                case '差旅费用报销单':
                  if (this.TRAVEL_moneyUse !== this.TRAVEL_moneySum) {
                    return this.$alert('剩余金额为： ' + SplitK(parseFloat(this.TRAVEL_moneySum) - parseFloat(this.TRAVEL_moneyUse)) + ' 元', '收款金额合计不足');
                  }
                  break;
                case '暂借款借支单':
                  if (this.TRAVEL_moneyUse !== this.TRAVEL_moneySum) {
                    console.log('TRAVEL_moneySum:' + this.TRAVEL_moneySum);
                    console.log('TRAVEL_moneyUse:' + this.TRAVEL_moneyUse);
                    console.log('数量：' + SplitK(this.TRAVEL_moneySum - this.TRAVEL_moneyUse));
                    return this.$alert('剩余金额为： ' + SplitK(this.TRAVEL_moneySum - this.TRAVEL_moneyUse) + ' 元', '收款金额合计不足');
                  }
                  break;
                case '奖励扣款报销单':
                  break;
                case '结算单':
                  break;
                }
                OPTION.call(this, option);
              });
            } else {
              this.$alert('报销金额为0元 没有意义！', '没有明细');
            }
          } else {
            this.$alert('必须上传附件！', '没有附件');
          }
        } else {
          OPTION.call(this, this.FORMOPTION('formDialog'));
        }
      },

      async dialogUploadOpen () {
        let {contentList} = await this.get('/workflowConfig/selectAuditors/' + this.formDialogUpload.id);
        this.dialogUpload.userId = contentList;
        this.dialogUpload.visible = true;
      },
      dialogUploadSave () {
        this.VALIDATE('formDialogUpload', async option => {
          try {
            await this.post('/reimbursement/submitReimbursement', option);
            this.dialogUpload.dialogInit.call(this);
          } catch (err) {
            console.error(err);
          }
        });
      },
      // 文件上传之前的钩子
      dialogUploadBefore (file) {
        let size = file.size;
        const isLt = file.size / 1024 / 1024 < 1;
        if (!isLt) {
          this.$message.error('上传附件大小不能大于 1MB!');
        }
        this.fileSize += size;
        this.summation += 1;
        console.log('this.fileSize', this.fileSize);
        console.log('this.summation', this.summation);
        if (this.fileSize < 209715200) {
          return isLt;
        } else {
          this.$message.error('上传的附件总大小不能大于 200MB!');
          return false;
        }
      },
      // 删除文件之前的钩子
      handleBeforeRemove (file) {
        return this.$confirm('您将删除这个附件。', '确认删除？', {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning',
        });
      },

      removeTravelUser (item) {
        if (this.formDialog.travel.length === 1) {
          return this.$alert('最少一位出差人员！', '提示');
        }
        let index = this.formDialog.travel.indexOf(item);
        if (index !== -1) {
          this.formDialog.travel.splice(index, 1);
        }
      },
      addTravelUser () {
        this.formDialog.travel.push({
          user: '',
          level: '',
        });
      },
    },
    watch: {
      'formDialog.loanMoney': function () {
        this.formDialog.loanMoneyCap = Nzh.cn.toMoney(this.formDialog.loanMoney);
        this.SET('TRAVEL_moneySum', parseFloat(this.formDialog.loanMoney));
      },
    },
    mounted: function () {
      let orgids = this.USER.user.orgId;
      let orgnames = this.USER.user.orgName;
      let len = orgids.length;
      let useroption = [];
      orgnames = orgnames.split('/');
      var i = 0;
      while(len > 0) {
        let as = {};
        as.value = orgids[i];
        as.label = orgnames[i];
        useroption[i] = as;
        i++;
        len--;
      }
      this.useroptions.options = useroption;
    },
  });
  /**
   * 报销主表
   reimbursementDate  (string, optional): 报销日期$$$true$false$false$$1$vNull$false,
   departmentId  (string, optional): 报销部门$$$true$false$false$$2$vNull$false,
   reimbursementCode  (string, optional): 报销编号$$$true$false$false$$3$vNull$false,
   money (string, optional): 报销金额合计$$$true$false$false$$4$vNull,vNumber$false,
   moneyCap  (string, optional): 核实金额（大写）$$$true$false$false$$5$vNull$false,
   borrowingMoney  (string, optional): 借款金额合计$$$true$false$false$$6$vNull,vNumber$false,
   enclosureNum  (string, optional): 附件数量$$$true$false$false$$7$vNumber$false,
   fileVoList  (string, optional): 附件列表$$$true$false$false$$8$$false,
   workflowconfigId  (string, optional): 所属流程$$$true$false$false$$9$$false,
   reimbursementUser (string, optional): 报销人$$$true$false$false$$9$$false,
   travelUsers  (string, optional): 出差人员$$$true$false$false$$9$$false,
   positionLeave   (string, optional): 职位级别$$$true$false$false$$9$$false,
   attributionDate  (string, optional): 归属期间$$$true$false$false$$9$$false,
   travelReason  (string, optional): 出差事由$$$true$false$false$$9$$false,

   borrower   (string, optional): 借款人 $$$true$false$false$$9$$false,
   departmentId  (string, optional): 报销部门$$$true$false$false$$9$vNull$false,
   loanMoney    (string, optional):  借款金额 $$$true$false$false$$9$$false,
   loanProject     (string, optional):  借款项目  $$$true$false$false$$9$$false,
   loanMoneyCap    (string, optional):  借款金额(大写) $$$true$false$false$$9$$false,
   repaymentDate      (string, optional):  还款时间  $$$true$false$false$$9$$false,
   */
</script>

<style lang="scss">
  .process {
    margin-left: 15px;
  }
  .process_select {
    width: 400px!important;
    @media screen and (max-width: 800px) {
      width: auto!important;
    }
  }
  .process_download {
    margin-top: 10px;
    float: right;
  }
  .__rbApply {
    .el-form-item {
      margin-bottom: 0;
    }
    .s-form {
      .el-form-item {
        margin-bottom: 15px;
      }
    }
    .el-collapse-item__content {
      padding-bottom: 0;
    }
    .other {
      border-bottom: 1px solid rgb(235, 238, 245);
      margin: 5px 0 5px;
    }
  }
</style>
